//
//  FileManager.m
//  ImGuider
//
//  Created by llt on 2017/4/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "FileManager.h"

@implementation FileManager

// ------------下载图片---------------------

+ (NSString *)pathInDownloadImageInDirectory:(NSString *)dirName url:(NSString *)url {
    
    NSString *fileName = [NSString stringWithFormat:@"%@.%@", [IGUtil md5:url],url.pathExtension];
    
    return [getFileDir(dirName) stringByAppendingPathComponent:fileName];
}

+ (UIImage *)getImageInDirectory:(NSString *)dirName url:(NSString *)url {
    
    NSString *imagePath = [self pathInDownloadImageInDirectory:dirName url:url];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:imagePath];
    
    if (!exist) {
        return nil;
    }
    
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

+ (void)saveImage:(UIImage *)image InDirectory:(NSString *)dirName url:(NSString *)url {
    
    if (image) {
        NSString *imagePath = [self pathInDownloadImageInDirectory:dirName url:url];
        NSData *imageData = UIImagePNGRepresentation(image);
        [imageData writeToFile:imagePath atomically:YES];
    }
}


+ (BOOL)deleteImageInDirectory:(NSString *)dirName url:url {
    
    return [self deleteCacheWithPath:[self pathInDownloadImageInDirectory:dirName url:url]];
}


+ (BOOL)deleteImageInDirectory:(NSString *)dirName {
    
    return [self deleteCacheWithPath:getFileDir(dirName)];
}

+ (NSUInteger)getImageSizeInDirectory:(NSString *)dirName  {
    
    return [self getCacheSize:getFileDir(dirName)];
}

// ------------网路请求缓存---------------------
//获取缓存fileName的完整地址
+ (NSString *)pathInResponseCacheDirectory:(NSString *)fileName {
    
    return [getFileDir(kPath_ResponseCache) stringByAppendingPathComponent:[IGUtil md5:fileName]];
}

//网络请求缓存
+ (BOOL)saveResponseData:(NSDictionary *)data toPath:(NSString *)requestPath {
    
    NSString *abslutePath = [NSString stringWithFormat:@"%@.plist", [self pathInResponseCacheDirectory:requestPath]];
    return [data writeToFile:abslutePath atomically:YES];
}
+ (id)loadResponseWithPath:(NSString *)requestPath {//返回一个NSDictionary类型的json数据
    
    NSString *abslutePath = [NSString stringWithFormat:@"%@.plist", [self pathInResponseCacheDirectory:requestPath]];
    return [NSMutableDictionary dictionaryWithContentsOfFile:abslutePath];
}

+ (BOOL)deleteResponseCache {
    
    return [self deleteCacheWithPath:getFileDir(kPath_ResponseCache)];
}
+ (NSUInteger)getResponseCacheSize {
    
    return [self getCacheSize:getFileDir(kPath_ResponseCache)];
}

//------------公用----------

NSString *getFileDir(NSString *fileDirName) {
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    NSString *documentDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
    NSString *fileFolder = [documentDir stringByAppendingPathComponent:fileDirName];
    
    BOOL isDir = NO;
    BOOL existed = [filemgr fileExistsAtPath:fileFolder isDirectory:&isDir];
    
    if (existed && isDir) {
        return fileFolder;
    }
    
    NSError *error = nil;
    if(![filemgr createDirectoryAtPath:fileFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
        IGLog(@"Failed to create cache directory at %@", fileFolder);
        fileFolder = nil;
    }
    return fileFolder;
}

+ (NSUInteger)getCacheSize:(NSString *)dirPath {
    //    NSString *dirPath = [self pathInCacheDirectory:kPath_ResponseCache];
    NSUInteger size = 0;
    NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:dirPath];
    for (NSString *fileName in fileEnumerator) {
        NSString *filePath = [dirPath stringByAppendingPathComponent:fileName];
        size += [self fileLengthForPath:filePath];
    }
    return size;
}

+ (BOOL)deleteCacheWithPath:(NSString *)dirPath {
    //    NSString *dirPath = [self pathInCacheDirectory:cachePath];
//    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:nil];
    bool isDeleted = false;
    if (existed) {
        
        isDeleted = [fileManager removeItemAtPath:dirPath error:nil];
    }
    return isDeleted;
}

+ (NSInteger)fileLengthForPath:(NSString *)path {
    
    NSUInteger fileLength = 0;
    NSFileManager *fileManager = [NSFileManager defaultManager]; // default is not thread safe
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
        if (!error && fileDict) {
            fileLength = [fileDict fileSize];
        }
    }
    return fileLength;
}

//将文件copy到tmp目录
+ (NSURL *)fileURLForBuggyWKWebView8:(NSURL *)fileURL {
    
    NSError *error = nil;
    if (!fileURL.fileURL || ![fileURL checkResourceIsReachableAndReturnError:&error]) {
        return nil;
    }
    // Create "/temp/www" directory
    NSFileManager *fileManager= [NSFileManager defaultManager];
    NSURL *temDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"www"];
    [fileManager createDirectoryAtURL:temDirURL withIntermediateDirectories:YES attributes:nil error:&error];
    
    NSURL *dstURL = [temDirURL URLByAppendingPathComponent:fileURL.lastPathComponent];
    // Now copy given file to the temp directory
    [fileManager removeItemAtURL:dstURL error:&error];
    [fileManager copyItemAtURL:fileURL toURL:dstURL error:&error];
    // Files in "/temp/www" load flawlesly :)
    return dstURL;
}

//----------------下载音频时的图片----------




@end
